//引入模块
const Koa = require("Koa")
const Router = require("koa-router")  //get post delete put 查增删改
const poolSql = require('./bd.js')   //数据库
const cors = require("koa2-cors")  //跨域
const bodyparser = require('koa-bodyparser') //获取body体

//实例化
const app = new Koa()
const router = new Router()
app.use(bodyparser())  //放在下面行就会拿不到body体
app.use(cors()) 
router.get("/index", async ctx => {
    ctx.state = 200
    ctx.body = '学习前端'
    console.log(123);
})

router.get("/query", async ctx => {
    ctx.state = 200
    // ctx.body = '学习前端11'
    try {
        let _sql = 'select * from commodity'
        let _data = await poolSql(_sql)
        ctx.body = {
            errorMessage: '',  //错误信息
            result: true,       //状态为true
            data: _data         //查询的数据
        }
    } catch (err) {
        ctx.body = {
            errorMessage: '查询失败',  //错误信息
            result: false,       //状态为true
            data: null         //查询的数据
        }

    }
})

router.post('/add', async ctx => {
    ctx.status = 200
    let _info = ctx.request.body
    console.log(_info);
    // console.log("req.body = "+JSON.stringify(ctx.request.body))
    if (!_info.name) {
        ctx.body = {
            errorMessage: '名称是必填项',
            result: false,
            data: null
        }
        return
    }
    try {
        let _sql = 'insert into commodity (name,number,price) VALUES (?,?,?)'
        let _vaule = [_info.name, _info.number, _info.price]
        await poolSql(_sql, _vaule)
        ctx.body = {
            errorMessage: '',
            result: true,

        }
    } catch (error) {
        ctx.body = {
            errorMessage: '添加失败哦',
            result: true,

        }

    }
})

router.post('/put', async ctx => {
    ctx.status = 200
    let _info = ctx.request.body
    console.log(_info);
    // console.log("req.body = "+JSON.stringify(ctx.request.body))
    if (!_info.id && !_info.name) {
        ctx.body = {
            errorMessage: '请填写必填项',
            result: false,
            data: null
        }
        return
    }
    try {
        let _sql = 'UPDATE commodity SET name=?, number=? ,price=? WHERE id = ?'
        let _vaule = [_info.name, _info.number, _info.price, _info.id]
        await poolSql(_sql, _vaule)
        ctx.body = {
            errorMessage: '',
            result: true,

        }
    } catch (error) {
        ctx.body = {
            errorMessage: '修改失败哦',
            result: true,

        }

    }
})
console.log(4561);

router.delete("/delete/:id",async ctx=>{
    ctx.status=200;
    console.log(ctx);
    let _info=ctx.params;
    try{
        let _sql="DELETE FROM commodity WHERE id=?";
        let _value =[_info.id];
        await poolSql(_sql,_value);
        ctx.body={
            errorMessage:"",
            result:true,
            data:null
        }        
    }catch(err){
        ctx.body={
            errorMessage:"删除失败",
            result:false,
            data:null
        }
    }
})

router.use("/api",router.routes());
//配置路由,解决跨域加上 use(cors)就可以了

app.use(router.routes()).use(router.allowedMethods())
 //解决跨域、获取body体 放在一行会404不知道为什么
// app.use(cors()).use(bodyparser()).use(router.routes()).use(router.allowedMethods());


//监听端口
app.listen(5000, () => {
    console.log('启动成功:5000');
})
